﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using VPN.DataContext;

namespace VPNService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        System.Threading.Thread t;

        protected override void OnStart(string[] args)
        {
            t = new System.Threading.Thread(ScanAccounts);
            t.Start();
        }

        private void ScanAccounts()
        {
            while (true)
            {
                AccountsCreateOrUpdate();
                System.Threading.Thread.Sleep(5 * 60 * 1000);
            }
        }

        private void AccountsCreateOrUpdate()
        {
            using (PODataContext pdc = new PODataContext("Data Source=(local);Initial Catalog=VPN;User ID=sa;password=123456"))
            //using (PODataContext pdc = new PODataContext(System.Configuration.ConfigurationManager.ConnectionStrings["default"].ConnectionString))
            {
                var pendings = pdc.Accounts
                    .Where(a => a.Status == 0)
                    .Take(10);
                foreach (Account a in pendings)
                {
                    a.Status = 1;
                    if (a.AccountCID == string.Empty)
                    {
                        CreateVPN(a);
                    }
                    else
                    {
                        UpdateVPN(a);
                    }
                }

                pdc.SubmitChanges();
            }
        }


        private string CreateVPN(Account account)
        {
            try
            {
                string pass = System.Math.Abs(Guid.NewGuid().GetHashCode()).ToString().Substring(0, 6);
                return account.AccountCID = WindowsAccountHelper.AddUser(account.AccountName, new string[] { account.Type, "VPN" }, pass, account.ExpireDate);
            }
            catch
            {
                account.Status = -5;
                return string.Empty;
            }
        }

        private void UpdateVPN(Account account)
        {
            try
            {
                WindowsAccountHelper.UpdateUser(account.AccountCID, account.AccountName, new string[] { account.Type, "VPN" }, string.Empty, account.ExpireDate, true);
            }
            catch
            {
                account.Status = -5;
            }
        }

        protected override void OnStop()
        {
            t.Abort();
        }
    }
}
